<?php

class Core_Controller_Router_Route_Module extends Zend_Controller_Router_Route_Module
{
	/**
	 * Matches a user submitted path. Assigns and returns an array of variables
	 * on a successful match.
	 *
	 * If a request object is registered, it uses its setModuleName(),
	 * setControllerName(), and setActionName() accessors to set those values.
	 * Always returns the values as an array.
	 *
	 * @param string $path Path used to match against this routing map
	 * @return array An array of assigned values or a false on a mismatch
	 */
	public function match($path, $partial = false)
	{
		$this->_setRequestKeys();

		$values = array();
		$params = array();

		if (!$partial) {
			$path = trim($path, self::URI_DELIMITER);
		} else {
			$matchedPath = $path;
		}

		if ($path != '') {
			$path = explode(self::URI_DELIMITER, $path);

			if ($this->_dispatcher && $this->_dispatcher->isValidModule($path[0])) {
				$values[$this->_moduleKey] = array_shift($path);
				$this->_moduleValid = true;
			}

			if (count($path) && !empty($values[$this->_moduleKey])) {
				$prefix 		= array();
				$moduleDir  = @rtrim($this->_dispatcher->getControllerDirectory($values[$this->_moduleKey]), '/').'/';
				$match 			= array();

				for($i = 0; $i < count($path) ; $i++)
				{
					$prefix[]		= ucfirst($path[$i]);
					if(is_file($moduleDir.implode('/' ,$prefix).'Controller.php'))
					{
						$match 		= $prefix;
					}
				}

				if(empty($match) && !empty($path))
				{
					$values[$this->_controllerKey] = array_shift($path);
				}

				$values[$this->_controllerKey] = implode('_', $match);
				$path = array_slice($path, count($match));

				unset($prefix);
				unset($moduleDir);
				unset($match);
			}
			
			if (count($path) && !empty($values[$this->_controllerKey])) {
				$values[$this->_actionKey] = array_shift($path);
			}

			if(!empty($values[$this->_actionKey]) && ($numSegs = count($path))) {
				for ($i = 0; $i < $numSegs; $i = $i + 2) {
					$key = urldecode($path[$i]);
					$val = isset($path[$i + 1]) ? urldecode($path[$i + 1]) : null;
					$params[$key] = (isset($params[$key]) ? (array_merge((array) $params[$key], array($val))): $val);
				}
			}
		}

		if ($partial) {
			$this->setMatchedPath($matchedPath);
		}
		
		$this->_values = $values + $params;
		return $values + $params;
	}
}